package io.renren.modules.generator.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.utils.ShiroUtils;
import io.renren.modules.generator.entity.EnclosureEntity;
import io.renren.modules.generator.service.EnclosureService;
import io.renren.modules.sys.entity.SysUserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;


/**
 * @author guijing
 * @email sunlightcs@gmail.com
 * @date 2022-03-28 20:16:37
 */
@RestController
@RequestMapping("student/enclosure")
public class EnclosureController {
    @Autowired
    private EnclosureService enclosureService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        Long userId = ShiroUtils.getUserId();
        params.put("userId", userId);
        Page<Map<String, Object>> page = new Page<>(Long.valueOf(String.valueOf(params.get("page"))), Long.valueOf(String.valueOf(params.get("limit"))));
        IPage<Map<String, Object>> mapIPage = enclosureService.studentEnclosureList(page, params);
        PageUtils newPage = new PageUtils(mapIPage);

        return R.ok().put("page", newPage);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{enclosureId}")
    public R info(@PathVariable("enclosureId") Integer enclosureId) {
        EnclosureEntity enclosure = enclosureService.getById(enclosureId);

        return R.ok().put("enclosure", enclosure);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody EnclosureEntity enclosure) {
        SysUserEntity userEntity = ShiroUtils.getUserEntity();
        enclosure.setClassId(userEntity.getClassId());
        enclosure.setStudentId(userEntity.getUserId());
        enclosure.setEnclosureDate(new Date());
        enclosureService.save(enclosure);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody EnclosureEntity enclosure) {
        enclosureService.updateById(enclosure);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete/{id}")
    public R delete(@PathVariable("id") Integer enclosureId) {
        try {
            enclosureService.deleteEnclosureById(enclosureId);
        } catch (Exception e) {
            throw new RRException("文件存储路径异常，请联系后台管理员");
        }

        return R.ok();
    }

}
